package com.hksj.common.config.handler;


import com.hksj.common.core.exception.ApplicationException;
import com.hksj.common.core.exception.VerifyCodeException;
import com.hksj.common.core.model.Rest;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Rest failed(Exception e) {
        e.printStackTrace();
        String msg = "服务器出现未知异常";
        Rest rest = Rest.fail(msg);
        //不合法、不正确的参数
        if (e instanceof IllegalArgumentException) {
            msg = e.getMessage();
        }
        //接口异常 前端页面传过来的参数与你controller接收的参数类型不匹配
        else if (e instanceof HttpMessageNotReadableException) {
            msg = "请求参数不合规，请校验后重新提交";
        }
        //参数校验异常
        else if (e instanceof MethodArgumentNotValidException) {
            msg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        }
        else if (e instanceof HttpRequestMethodNotSupportedException) {
            msg = "不支持的请求方式";
        }

        else if(e instanceof ApplicationException){
            msg = e.getMessage();
            rest.setCode(((ApplicationException) e).getCode());
            rest.setData(e.getMessage());
        }

        else if(e instanceof VerifyCodeException){
            msg = e.getMessage();
            rest.setCode(((VerifyCodeException) e).getCode());
            rest.setData(e.getMessage());
        }

        else if (e instanceof RuntimeException && StringUtils.hasText(e.getMessage())) {
            msg = e.getMessage();
        }
        rest.setMsg(msg);
        return rest;
    }

}

